package com.station.service.impl;

import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.station.param.request.*;
import com.station.param.request.FCreateOrgId;
import com.station.param.request.FUseOrgId;
import com.station.param.request.materials.Model;
import com.station.param.request.materials.SubHeadEntity;
import com.station.param.request.materials.SubHeadEntity1;
import com.station.param.request.materials.SubHeadEntity3;
import com.station.param.request.supplier.*;
import com.station.param.response.UnitDto;
import com.station.service.BasicDataService;
import com.station.service.mapper.ItemMapper;
import com.station.service.mapper.RelateDunitsMapper;
import com.station.service.mapper.UnitMapper;
import com.station.utils.KingDeeUtils;
import com.station.utils.R;
import com.station.utils.StringUtils;
import com.station.vo.ItemVo;
import com.station.vo.RelateDunitVo;
import com.station.vo.UnitVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: dongfangyu
 * @Date: 2025/9/17
 */
@Slf4j
@Service
public class BasicDataServiceImpl implements BasicDataService {

    @Autowired
    private RelateDunitsMapper relateDunitsMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private UnitMapper unitMapper;


    @Value("${rd.bld.vendorId}")
    private String vendorId;
    /**
     * 供应商业务对象标识
     */
    private static final String BD_SUPPLIER = "BD_Supplier";
    /**
     * 物料业务对象标识
     */
    private static final String BD_MATERIAL = "BD_MATERIAL";
    /**
     * 计量单位对象标识
     */
    private static final String BD_UNIT = "BD_UNIT";
    /**
     * 分组前缀
     */
    private static final String F_GROUP_PREFIX = "03.13";
    /**
     * 供应商分组
     */
    private static final String F_SUPPLIER_GROUP_PREFIX = "08";
    /**
     * 创建组织
     */
    private static final String F_CREATE_ORG_ID = "100";
    /**
     * 使用组织
     */
    private static final String F_USE_ORG_ID = "100";


    @Override
    public R createSupplier(RelateDunitVo relateDunitVo) {
        if (null == relateDunitVo.getRelatedName()) {
            return R.error("供应商名称不能为空！");
        }
        if (null == relateDunitVo.getRelatedCode()) {
            return R.error("供应商编码不能为空！");
        }
        SupplierData supplierData = new SupplierData();
        SupplierModel supplierModel = new SupplierModel();
        supplierModel.setFNumber(relateDunitVo.getRelatedCode());
        supplierModel.setFName(relateDunitVo.getRelatedName());
        supplierModel.setFCreateOrgId(new com.station.param.request.supplier.FCreateOrgId(F_CREATE_ORG_ID));
        supplierModel.setFUseOrgId(new com.station.param.request.supplier.FUseOrgId(F_USE_ORG_ID));
        FFinanceInfo fFinanceInfo = new FFinanceInfo();
        fFinanceInfo.setFPayCurrencyId(new com.station.param.request.supplier.FPayCurrencyId("PRE001"));
        supplierModel.setFFinanceInfo(fFinanceInfo);
        supplierModel.setFGroup(new com.station.param.request.supplier.FGroup(F_SUPPLIER_GROUP_PREFIX));
        supplierData.setIsAutoSubmitAndAudit(true);
        supplierData.setModel(supplierModel);
        Gson requestGson = new Gson();
        String jsonData = requestGson.toJson(supplierData);
        RepoResult repoResult = KingDeeUtils.save(BD_SUPPLIER, jsonData);
        if (repoResult.getResponseStatus().isIsSuccess()) {
            return R.ok().put("data", repoResult.getResult());
        } else {
            return R.error(repoResult.getResponseStatus().getErrors().toString());
        }
    }


    @Override
    public List<String> selectSupplierList() {
        return relateDunitsMapper.selectRelateDunits();
    }


    @Override
    public R createMaterials(ItemVo itemVo) {
        if (StringUtils.isEmpty(itemVo.getItemName())) {
            return R.error("物料名称不能为空！");
        }
        if (StringUtils.isEmpty(itemVo.getBarcode())) {
            return R.error("物料条码不能为空！");
        }
        if (StringUtils.isEmpty(itemVo.getItemId())) {
            return R.error("商品id不能为空！");
        }
        if (StringUtils.isEmpty(itemVo.getCatCode())) {
            return R.error("物料分类编码不能为空！");
        }
        String requestJson = this.getMaterialsString(itemVo);
        RepoResult repoResult = KingDeeUtils.save(BD_MATERIAL, requestJson);
        if (repoResult.getResponseStatus().isIsSuccess()) {
            return R.ok().put("data", repoResult.getResult());
        } else {
            return R.error(repoResult.getResponseStatus().getErrors().toString());
        }
    }

    private String getMaterialsString(ItemVo itemVo) {
        ProductRequest productRequest = new ProductRequest();
        Model model = new Model();
        model.setFCreateOrgId(new FCreateOrgId(F_CREATE_ORG_ID));
        model.setFUseOrgId(new FUseOrgId(F_USE_ORG_ID));
        model.setFName(itemVo.getItemName());
        String cartId = null;
        if (StringUtils.isEmpty(itemVo.getParentCode())) {
            cartId = itemVo.getCatCode();
        } else {
            cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
        }
        model.setFNumber(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId());
        model.setFMaterialGroup(new FMaterialGroup(F_GROUP_PREFIX + "." + cartId));
        SubHeadEntity subHeadEntity = new SubHeadEntity();
        subHeadEntity.setFBARCODE(itemVo.getBarcode());
        subHeadEntity.setFErpClsID("1");
        UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), itemVo.getUnit());
        String unitCode = "Pcs";
        if (null != unitVo && null != unitVo.getUnitCode()) {
            unitCode = unitVo.getUnitCode();
        }
        subHeadEntity.setFCategoryID(new FCategoryID("CHLB01_SYS"));
        subHeadEntity.setFBaseUnitId(new FBaseUnitId(unitCode));
        subHeadEntity.setFSuite("0");
        model.setSubHeadEntity(subHeadEntity);

        SubHeadEntity1 subHeadEntity1 = new SubHeadEntity1();
        subHeadEntity1.setFStoreUnitID(new FStoreUnitID(unitCode));
        subHeadEntity1.setFUnitConvertDir("1");
        subHeadEntity1.setFCurrencyId(new FCurrencyId("PRE001"));
        subHeadEntity1.setFSNManageType("1");
        subHeadEntity1.setFSNGenerateTime("1");
        model.setSubHeadEntity1(subHeadEntity1);


        SubHeadEntity3 subHeadEntity3 = new SubHeadEntity3();
        subHeadEntity3.setFPurchaseUnitId(new FPurchaseUnitId(unitCode));
        subHeadEntity3.setFPurchasePriceUnitId(new FPurchasePriceUnitId(unitCode));
        subHeadEntity3.setFQuotaType("1");
        model.setSubHeadEntity3(subHeadEntity3);

        FBarCodeEntity_CMK[] fBarCodeEntityCmk = new FBarCodeEntity_CMK[1];
        fBarCodeEntityCmk[0] = new FBarCodeEntity_CMK();
        fBarCodeEntityCmk[0].setFCodeType_CMK("0");
        fBarCodeEntityCmk[0].setFUnitIdCmk(new FUnitId_CMK("0"));
        model.setFBarCodeEntity_CMK(fBarCodeEntityCmk);
        productRequest.setModel(model);
        productRequest.setIsAutoSubmitAndAudit(true);
        Gson requestGson = new Gson();
        String requestJson = requestGson.toJson(productRequest);
        return requestJson;
    }

    @Override
    public R batchCreateMaterials() {
        List<ItemVo> itemVos = itemMapper.queryItemList(Long.valueOf(vendorId));
        if (!CollectionUtils.isEmpty(itemVos)) {
            Model[] models = new Model[itemVos.size()];
            int index = 0;
            for (ItemVo itemVo : itemVos) {
                Model model = new Model();
                model.setFCreateOrgId(new FCreateOrgId(F_CREATE_ORG_ID));
                model.setFUseOrgId(new FUseOrgId(F_USE_ORG_ID));
                model.setFName(itemVo.getItemName());
                String cartId = null;
                if (StringUtils.isEmpty(itemVo.getParentCode())) {
                    cartId = itemVo.getCatCode();
                } else {
                    cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                }
                UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), itemVo.getUnit());
                String unitCode = "Pcs";
                if (null != unitVo && null != unitVo.getUnitCode()) {
                    unitCode = unitVo.getUnitCode();
                }
                model.setFNumber(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId());
                model.setFMaterialGroup(new FMaterialGroup(F_GROUP_PREFIX + "." + cartId));
                SubHeadEntity subHeadEntity = new SubHeadEntity();
                subHeadEntity.setFBARCODE(itemVo.getBarcode());
                subHeadEntity.setFErpClsID("1");
                subHeadEntity.setFCategoryID(new FCategoryID("CHLB01_SYS"));
                subHeadEntity.setFBaseUnitId(new FBaseUnitId(unitCode));
                subHeadEntity.setFSuite("0");
                model.setSubHeadEntity(subHeadEntity);

                SubHeadEntity1 subHeadEntity1 = new SubHeadEntity1();
                subHeadEntity1.setFStoreUnitID(new FStoreUnitID(unitCode));
                subHeadEntity1.setFUnitConvertDir("1");
                subHeadEntity1.setFCurrencyId(new FCurrencyId("PRE001"));
                subHeadEntity1.setFSNManageType("1");
                subHeadEntity1.setFSNGenerateTime("1");
                model.setSubHeadEntity1(subHeadEntity1);

                SubHeadEntity3 subHeadEntity3 = new SubHeadEntity3();
                subHeadEntity3.setFPurchaseUnitId(new FPurchaseUnitId(unitCode));
                subHeadEntity3.setFPurchasePriceUnitId(new FPurchasePriceUnitId(unitCode));
                subHeadEntity3.setFQuotaType("1");
                model.setSubHeadEntity3(subHeadEntity3);

                FBarCodeEntity_CMK[] fBarCodeEntityCmk = new FBarCodeEntity_CMK[1];
                fBarCodeEntityCmk[0] = new FBarCodeEntity_CMK();
                fBarCodeEntityCmk[0].setFCodeType_CMK("0");
                fBarCodeEntityCmk[0].setFUnitIdCmk(new FUnitId_CMK("0"));
                model.setFBarCodeEntity_CMK(fBarCodeEntityCmk);
                models[index++] = model;
            }
            ProductBatchRequest productRequest = new ProductBatchRequest();
            productRequest.setIsAutoSubmitAndAudit(true);
            productRequest.setModel(models);
            Gson requestGson = new Gson();
            String requestJson = requestGson.toJson(productRequest);
            RepoResult repoResult = KingDeeUtils.batchSave(BD_MATERIAL, requestJson);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                return R.ok().put("data", repoResult.getResult());
            } else {
                return R.error(repoResult.getResponseStatus().getErrors().toString());
            }
        }
        return R.ok("未查询到物料数据！");
    }

    @Override
    public R batchCreateSupplier() {
        List<RelateDunitVo> relateDunitVos = relateDunitsMapper.selectRelateDunitList(Long.valueOf(vendorId));
        if (!CollectionUtils.isEmpty(relateDunitVos)) {
            SupplierModel[] supplierModels = new SupplierModel[relateDunitVos.size()];
            int index = 0;
            for (RelateDunitVo relateDunitVo : relateDunitVos) {
                SupplierModel supplierModel = new SupplierModel();
                supplierModel.setFCreateOrgId(new com.station.param.request.supplier.FCreateOrgId(F_CREATE_ORG_ID));
                supplierModel.setFUseOrgId(new com.station.param.request.supplier.FUseOrgId(F_USE_ORG_ID));
                FFinanceInfo fFinanceInfo = new FFinanceInfo();
                fFinanceInfo.setFPayCurrencyId(new com.station.param.request.supplier.FPayCurrencyId("PRE001"));
                supplierModel.setFFinanceInfo(fFinanceInfo);
                supplierModel.setFGroup(new com.station.param.request.supplier.FGroup(F_SUPPLIER_GROUP_PREFIX));
                supplierModel.setFName(relateDunitVo.getRelatedName());
                supplierModel.setFNumber(relateDunitVo.getRelatedCode());
                supplierModels[index] = supplierModel;
                index++;
            }
            SupplierBatchData supplierBatchData = new SupplierBatchData();
            supplierBatchData.setIsAutoSubmitAndAudit(true);
            supplierBatchData.setModel(supplierModels);
            String jsonData = new Gson().toJson(supplierBatchData);
            RepoResult repoResult = KingDeeUtils.batchSave(BD_SUPPLIER, jsonData);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                return R.ok().put("data", repoResult.getResult());
            } else {
                return R.error(repoResult.getResponseStatus().getErrors().toString());
            }
        }
        return R.ok("未查询到供应商数据！");
    }

    @Override
    public R batchSyncUnit() {
        try {
            List<UnitVo> unitVoList = new ArrayList<>();
            String jsonData = "{\"FormId\":\"BD_UNIT\",\"FieldKeys\":\"FName,FNumber\",\"FilterString\":[],\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":2000,\"SubSystemId\":\"\"}";
            List<List<Object>> resultList = KingDeeUtils.executeBillQuery(jsonData);
            if (!CollectionUtils.isEmpty(resultList)) {
                List<UnitDto> unitList = new ArrayList<>();
                unitList = resultList.stream().filter(Objects::nonNull).filter(list -> list.size() >= 2)
                        .map(list -> UnitDto.builder().FName(list.get(0).toString()).FNumber(list.get(1).toString()).build())
                        .collect(Collectors.toList());
                Date now = new Date();
                for (UnitDto unitDto : unitList) {
                    UnitVo build = UnitVo.builder().vendorId(vendorId).unitName(unitDto.getFName()).unitCode(unitDto.getFNumber()).createDate(now).modifyDate(now).df(0).build();
                    unitVoList.add(build);
                }
            }
            //根据单位名称新增或更新unit表中的数据
            if (!CollectionUtils.isEmpty(unitVoList)) {
                try {
                    int flag = unitMapper.batchInsertOrUpdateUnit(unitVoList);
                    if (flag >= 0) {
                        return R.ok("计量单位同步成功！");
                    }
                } catch (Exception e) {
                    return R.error("计量单位同步失败！ " + e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("计量单位同步失败！ " + e.getMessage());
        }
        return R.ok();
    }
}
